Page({
  data: {
    order: null,
    messages: [],
    inputMsg: '',
    showOrderDetail: true,
    userId: null,
    orderId: null,
    technicianInfo: null
  },
  onLoad(options) {
    const { orderId, userId } = options;
    this.setData({ 
      orderId, 
      userId,
      technicianInfo: wx.getStorageSync('technicianInfo')
    });
    this.loadOrderDetail(orderId);
    this.loadMessages(orderId);
  },
  onShow() {
    // 每次页面显示都刷新订单详情
    if (this.data.orderId) {
      this.loadOrderDetail(this.data.orderId);
    }
  },
  async loadOrderDetail(orderId) {
    try {
      const res = await getApp().request({
        url: `/api/orders/${orderId}`,
        method: 'GET'
      });
      if (res.data) {
        this.setData({ order: res.data });
      }
    } catch (err) {
      console.error('加载订单详情失败:', err);
      wx.showToast({
        title: '加载订单详情失败',
        icon: 'none'
      });
    }
  },
  async loadMessages(orderId) {
    try {
      const res = await getApp().request({
        url: `/api/messages?orderId=${orderId}`,
        method: 'GET'
      });
      
      if (res.data) {
        const technicianId = String(this.data.technicianInfo.id);
        const messages = res.data.map(msg => {
          const senderIdStr = String(msg.senderId);
          const isSelf = senderIdStr === technicianId;
          console.log('消息 senderId:', senderIdStr, '工程师 id:', technicianId, 'isSelf:', isSelf, '内容:', msg.content);
          return {
            ...msg,
            isSelf,
            time: new Date(msg.createTime).toLocaleString()
          };
        });
        this.setData({ messages });
      }
    } catch (error) {
      console.error('加载消息失败:', error);
      wx.showToast({
        title: '加载消息失败',
        icon: 'none'
      });
    }
  },
  onInput(e) {
    this.setData({
      inputMsg: e.detail.value
    });
  },
  async sendMsg() {
    if (!this.data.inputMsg.trim()) {
      wx.showToast({
        title: '消息不能为空',
        icon: 'none'
      });
      return;
    }

    try {
      const res = await getApp().request({
        url: '/api/messages',
        method: 'POST',
        data: {
          orderId: this.data.orderId,
          content: this.data.inputMsg,
          senderId: this.data.technicianInfo.id,
          receiverId: this.data.order.userId
        }
      });

      if (res.data) {
        // 构造完整消息对象，内容用本地输入
        const newMessage = {
          id: res.data.id, // 用后端返回的id
          content: this.data.inputMsg, // 用本地输入内容
          senderId: this.data.technicianInfo.id,
          receiverId: this.data.order.userId,
          isSelf: true,
          avatar: this.data.technicianInfo.avatar || '/assets/icons/default-avatar.png',
          time: new Date().toLocaleString()
        };
        this.setData({
          messages: [...this.data.messages, newMessage],
          inputMsg: ''
        });
      }
    } catch (error) {
      console.error('发送消息失败:', error);
      wx.showToast({
        title: '发送消息失败',
        icon: 'none'
      });
    }
  },
  async acceptOrder() {
    try {
      const res = await getApp().request({
        url: `/api/orders/${this.data.orderId}/accept`,
        method: 'POST'
      });
      if (res.data && res.data.success) {
        wx.showToast({
          title: '接单成功',
          icon: 'success'
        });
        this.loadOrderDetail(this.data.orderId);
      }
    } catch (err) {
      console.error('接单失败:', err);
      wx.showToast({
        title: '接单失败',
        icon: 'none'
      });
    }
  },
  closeOrderDetail() {
    this.setData({ showOrderDetail: false });
  },
  async finishOrder() {
    try {
      const res = await getApp().request({
        url: `/api/orders/${this.data.orderId}/finish`,
        method: 'PUT'
      });
      if (res.data && res.data.success) {
        wx.showToast({
          title: '订单已完成',
          icon: 'success'
        });
        this.loadOrderDetail(this.data.orderId);
      }
    } catch (err) {
      console.error('完成订单失败:', err);
      wx.showToast({
        title: '完成订单失败',
        icon: 'none'
      });
    }
  }
}); 